import { 
  BoxGeometry,
  CircleBufferGeometry,
  Color,
  DoubleSide,
  Group,
  LineBasicMaterial,
  LineSegments,
  Mesh,
  MeshBasicMaterial,
  Path,
  PerspectiveCamera, 
  Scene, Shape, ShapeGeometry, Vector2, WebGLRenderer, WireframeGeometry 
} from 'three'
import stats from '../../utils/stats'
import dat from 'dat.gui'
import { TrackballControls } from 'three/examples/jsm/controls/TrackballControls'

const scene = new Scene()
const camera = new PerspectiveCamera(45, window.innerWidth/window.innerHeight, 0.1, 1000)
camera.position.set(-11, 14, 24)
camera.lookAt(0, 0, 0)

const group  = new Group()
const matertial = new MeshBasicMaterial({
  color: 0xff9900,
  side: DoubleSide
})
const geometry = new BoxGeometry(2, 2, 2)
const shape = new Mesh(geometry, matertial)
group.add(shape)
const wireFrame = new WireframeGeometry(geometry)
const lines = new LineSegments(wireFrame)
group.add(lines)

scene.add(group)

const controls = {
  width: geometry.parameters.width,
  height: geometry.parameters.height,
  depth: geometry.parameters.depth,
  segments: geometry.parameters.depthSegments || 1,
  color: matertial.color.getStyle(),
  redraw() {
    let segments = ~~this.segments
    // 生成新几何体
    let newGeometry = new BoxGeometry(this.width, this.height, this.depth, segments, segments, segments)

    ;(group.children[0] as Mesh).geometry.dispose()
    ;(group.children[1] as Mesh).geometry.dispose()

    ;(group.children[0] as Mesh).geometry = newGeometry;
    (group.children[1] as Mesh).geometry = new WireframeGeometry(newGeometry);
  }
}

const gui = new dat.GUI()
gui.addColor(controls, 'color').onChange(e => {
  matertial.color.set(new Color(e))
})
gui.add(controls, 'segments', 1, 10, 1).onChange(e => controls.redraw())

const renderer = new WebGLRenderer({ antialias: true })
renderer.setPixelRatio(window.devicePixelRatio)
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.setClearColor(0x000000)

document.body.appendChild(renderer.domElement)
const trackballControls = new TrackballControls(camera, renderer.domElement)

function render() {
  stats.update()
  trackballControls.update()

  group.rotation.y += 0.01

  requestAnimationFrame(render)
  renderer.render(scene, camera)
}

render()